<template>
  <el-container class="app_container flex">
    <Aside @handleNodeClick="handleNodeClick" />
    <el-main class="app_main flex">
      <Breadcrumb title="数据监测" />
      <div class="app_content">
        <el-form ref="searchForm" :model="searchMap">
          <el-row class="flex serach_item">
            <el-button v-for="(item, index) in this.deviceClassList" :key="'sys' + item.deviceTypeId + index" type="primary" :class="setDeviceClassifyActive(item.deviceTypeId)" @click="getDeviceType(item)">{{ item.deviceTypeName }}</el-button>
          </el-row>
          <el-row class="flex serach_item">
            <span class="label-tip">设备类型：</span>
            <el-button v-for="(item, index) in this.deviceTypeList" :key="'type' + item.deviceTypeId + index" type="primary" :class="setDeviceTypeActive(item.deviceTypeId)" @click="getList(item)">{{ item.deviceTypeName }}（{{ item.deviceNum }}）</el-button>
          </el-row>
          <el-row class="flex serach_item">
            <span class="label-tip">设备状态：</span>
            <el-button v-for="(item, index) in device_status_arr" :key="item.value + index" type="primary" :class="setDeviceStatusActive(item.value)" @click="setDeviceStatus(item)">{{ item.label }}（{{ item.deviceNum }}）</el-button>
          </el-row>
          <div class="serach_wrapper flex-space-between el-form--inline">
            <div class="search flex">
              <el-form-item prop="deviceName" size="small">
                <el-input v-model="searchMap.deviceName" placeholder="请输入设备名称"></el-input>
              </el-form-item>
              <el-form-item prop="enableStatus" size="small">
                <el-select v-model="searchMap.enableStatus" placeholder="是否启用" clearable>
                  <el-option v-for="dict in dict.type.device_enable_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>

              <el-form-item class="flex">
                <el-button @click="handleSearch()" class="btn_primary">查询</el-button>
                <el-button @click="handleReset()" class="btn_cancel">重置</el-button>
              </el-form-item>
            </div>
          </div>
        </el-form>

        <el-table :data="dataList" v-loading="loading" stripe class="per_table" style="width: 100%" :height="winTableH">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="deviceTypeName" label="设备类型"></el-table-column>
          <el-table-column prop="deviceStatus" label="设备状态">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.device_status" :value="scope.row.deviceStatus" />
            </template>
          </el-table-column>
          <el-table-column prop="deviceCode" label="设备编号"></el-table-column>
          <el-table-column prop="deviceName" label="设备名称"></el-table-column>
          <el-table-column prop="installPosition" label="设备位置"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column key="enableStatus" label="是否启用">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.device_enable_status" :value="scope.row.enableStatus" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <div class="">
                <span type="text" class="tag_primary" size="small" @click="handleDetail(scope.row)">查看详情</span>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <Pagination v-show="total > 0" :total="total" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize" @change="getList"></Pagination>
        <!-- 分页over -->

      </div>

      <!-- 弹窗 详情 -->
      <el-dialog title="设备详情" class="large_dialog" :visible.sync="dialogVisibleDetail" top="10px" :close-on-click-modal="false" :key="Math.random()">
        <DeviceDetail :details="descData" :dictMap="dict" :key="Math.random()"></DeviceDetail>
      </el-dialog>
      <!-- 弹窗 详情 over -->

    </el-main>
  </el-container>
</template>

<script>
import { listDeviceData, delDeviceData, statDeviceTypeUnderDeviceNum } from '@/api/system/device/management';
import { listDeviceTypesData } from '@/api/system/device/types';
import { getStatDeviceStatusCount } from '@/api/dataMonitoring';
import { getProjectPointControl } from '@/api';
import Aside from '@/components/Aside';
import Breadcrumb from '@/components/Breadcrumb';
import DeviceDetail from '@/views/dataMonitoring/detail'
import { EventBus } from '@/utils/eventbus';

export default {
  name: 'DeviceManagement',
  dicts: ['device_status', 'device_enable_status', 'alarm_type'],
  data() {
    return {
      // 新增或编辑弹窗的默认选中tab
      tabActive: 0,
      // 遮罩层
      loading: false,
      // 设备系统分类列表
      deviceClassList: [],
      // 设备类型列表
      deviceTypeList: [],
      // 搜索条件
      searchMap: {
        pageNum: 1,
        pageSize: 10,
        deptId: '',
        deviceClassifyId: '',
        deviceName: '',
        deviceStatus: '',
        deviceTypeId: '',
        deviceTypeKey: '',
        enableStatus: '',
        projectPointName: "",
        projectPointId: ""
      },
      // 总条数
      total: 0,
      // 告警列表
      alarmList: [],
      // 数据列表
      dataList: [],
      // 详情数据
      descData: {},
      // 详情弹窗显示隐藏
      dialogVisibleDetail: false,
      // 设备类型统计总数
      sum: 0,
      // 设备状态数组
      device_status_arr:[],
    };
  },
  created() {
    EventBus.$on('currentTree', data => {
      this.searchMap.deptId = data.id
      this.searchMap.projectPointName = data.projectPointName
      this.searchMap.projectPointId = data.projectPointId
      this.activeStatus = ''

      this.getListDeviceTypesData()
    })

  },
  computed: {
  },
  watch: {},
  methods: {
    // 获取设备列表
    getList(data) {
      if (data) {
        data.deviceTypeId !== undefined && (this.searchMap.deviceTypeId = data.deviceTypeId)
      } else {
        this.activeDevice = ''
      }
      this.loading = true;
      if (!this.searchMap.deptId) {
        this.$message({
          message: "请先选择项目点类型",
          type: "warning",
        });
        return
      }
      if (!this.searchMap.deviceClassifyId) {
        this.$message({
          message: "请先选择设备系统分类",
          type: "warning",
        });
        return
      }
      listDeviceData(this.searchMap).then(res => {
        if (res && 200 === res.code) {
          this.dataList = res.rows;
          this.total = res.total;
        }
        this.loading = false;
      });
    },
    // 获取设备系统分类
    getListDeviceTypesData() {
      listDeviceTypesData({
        pid: 0
      }).then(res => {
        if (res && 200 === res.code) {
          this.deviceClassList = res.data
          if (this.deviceClassList.length) {
            this.searchMap.deviceClassifyId = this.deviceClassList[0].deviceTypeId
            this.searchMap.pageNum = 1;
            this.getDeviceType(this.deviceClassList[0], true)
          }
        }
      })
    },
    // 获取设备类型列表
    getDeviceType(data, isInit) {
      if (this.searchMap.deviceClassifyId === data.deviceTypeId && !isInit) return
      this.searchMap.deviceClassifyId = data.deviceTypeId
      listDeviceTypesData({ pid: data.deviceTypeId }).then(res => {
        if (res && 200 === res.code) {
          this.deviceTypeList = res.data
          this.toGetStatDeviceTypeUnderDeviceNum()
        }
      });
    },
    // 获取设备类型列表数量
    toGetStatDeviceTypeUnderDeviceNum() {
      statDeviceTypeUnderDeviceNum(this.searchMap).then(res => {
        if (res && 200 == res.code) {
          let arr = this.deviceTypeList.map(item => {
            let obj = res.data.filter(item2 => item2.deviceType.deviceTypeId == item.deviceTypeId)[0]
            if (obj) {
              item.deviceNum = obj.deviceNum
            }
            return item
          })

          this.sum = arr.reduce((total, item) => total + item.deviceNum, 0)
          this.deviceTypeList = [{ deviceTypeName: "全部", deviceNum: this.sum, deviceTypeId: '' }].concat(arr)
          
          this.toGetStatDeviceStatusCount();
          this.getList();
        }
      })
    },
    // 获取统计设备状态的数量
    toGetStatDeviceStatusCount(){
      getStatDeviceStatusCount(this.searchMap).then(res => {
        if(res && 200 == res.code){
          this.device_status_arr = [{label: "全部", value: '', deviceNum: res.data['全部']}].concat(this.dict.type.device_status.map(item => {
            item.deviceNum = res.data[item.label]
            return item
          }))
        }
      })
    },
    // 节点点击触发
    handleNodeClick(data) {
      this.searchMap.deptId = data.id;
      this.searchMap.projectPointName = data.projectPointName
      this.searchMap.projectPointId = data.projectPointId
      this.searchMap.pageNum = 1;
      this.getListDeviceTypesData()
    },
    /** 查询按钮操作 */
    handleSearch() {
      this.searchMap.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    handleReset() {
      this.searchMap.deviceName = ''
      this.searchMap.deviceStatus = ''
      this.searchMap.enableStatus = ''
      this.getList()
    },
    // 弹窗详情-取消
    cancelDetail() {
      this.dialogVisibleDetail = false;
    },
    // 设备系统类型设置选中项
    setDeviceClassifyActive(id) {
      return id === this.searchMap.deviceClassifyId ? "btn_group_active" : "btn_group"
    },
    // 设备类型设置选中项
    setDeviceTypeActive(id) {
      this.activeDevice = id === this.searchMap.deviceTypeId ? "btn_group_active" : "btn_group"
      return this.activeDevice
    },
    // 设备状态设置选中项
    setDeviceStatusActive(id){
      this.activeStatus = id === this.searchMap.deviceStatus ? "btn_group_active" : "btn_group"
      return this.activeStatus
    },
    // 设置弹窗tab选中项
    setTabActive(cur) {
      this.tabActive = cur
    },
    // 详情弹窗
    async handleDetail(row){
      this.dialogVisibleDetail = true;

      row.deviceStatusLabel = this.getDictLabel(this.dict.type.device_status, row.deviceStatus)
      row.enableStatusLabel = this.getDictLabel(this.dict.type.device_enable_status, row.enableStatus)
      row.deptId = this.searchMap.deptId

      // 查询项目点信息详情
      // let res = await getProjectPointControl(row.projectPointId)
      // if(res && 200 == res.code){
      //   row.projectPointName = res.data.projectPointName
      // }

      this.descData = row
    },
    // 点击设备状态
    setDeviceStatus(item){
      this.searchMap.deviceStatus = item.value
      this.getList(item)
    },
    // 通过value获取字典的label
    getDictLabel(list, value){
      let item = list.filter(item => item.value == value)
      if(item.length){
        return item[0].label
      } else {
        return ''
      }
    }
  },
  components: {
    Aside,
    Breadcrumb,
    DeviceDetail
  },
  beforeDestroy() {
    EventBus.$off("currentTree")
  }
};
</script>

<style lang="less">
.serach_item {
  flex-wrap: wrap;
  margin-bottom: 15px;

  button {
    margin-bottom: 15px;
  }
}

.btn_group_active.el-button,
.btn_group.el-button {
  min-width: 100px;
  width: auto;
}

.label-tip {
  margin-right: 15px;
  font-size: 14px;
  line-height: 32px;
  margin-bottom: 15px;
}
</style>
